package com.weilian.ordering.util;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;

public class CacheManager {
	public static Bitmap get(String key) {
		SoftReference<Bitmap> softReference = imageCache.get(key);   
		Bitmap bitmap = softReference.get();   
        if (bitmap != null&&!bitmap.isRecycled()) {
            return bitmap;
        }else
		return null;
	}

//	public static void checkCache(){
//		if(imageCache.size()>30){
//			System.out.println("clear cache");
//			list.clear();
//			imageCache.clear();
//		}
//	}
	
	public static boolean check(String key) {
		
	
		if (imageCache.containsKey(key)) {
			//System.out.println("Cache Check:"+key);
			return true;
		} else
			return false;
	}

	public static void add(String key, Bitmap bitmap) {

		imageCache.put(key, new SoftReference<Bitmap>(bitmap));

		list.add(key);
//		if (list.size() >= MAX_CACHE) {
//			System.out.println("clear larger cache");
//			for (int i = 0; i < MAX_CACHE / 10; i++) {
//				String keys = list.get(i);
//				recycle(keys);
//			}
//		}
	}
	
	private static void recycle(String key){
		SoftReference<Bitmap> softReference = imageCache.get(key);
		if(softReference!=null){
			try{
				Bitmap bitmap = softReference.get();
				if(bitmap!=null&&!bitmap.isRecycled()){
					bitmap.recycle();
					bitmap = null;
					imageCache.remove(key);
					list.remove(key);
				}
			}catch (Error e) {
				// TODO: handle exception
				System.out.println("shit fuck");
			}
		}
	}
	
	public void update() {

	}
	
	public static void delCache(){
		for(String key:list){
			if(imageCache.containsKey(key)){
				SoftReference<Bitmap> softReference = imageCache.get(key);
				if(softReference!=null){
					Bitmap bitmap = softReference.get();
					if(bitmap!=null&&!bitmap.isRecycled()){
						bitmap.recycle();
						bitmap = null;
					}
				}
			}
		}
		list.clear();
		imageCache.clear();
	}
	
	public static void clear(){
		System.out.println("clear all cache");
		int size = list.size()/2;
		for(int i=0;i<size;i++){
			String key = list.get(i);
			recycle(key);
		}
//		list.clear();
//		imageCache.clear();
	}

	private static int MAX_CACHE = 500;
	private static ArrayList<String> list = new ArrayList<String>();
	public static HashMap<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();
}
